package com.example.location.controller;

import com.example.location.bean.User;
import com.example.location.service.UserService;
import com.example.location.until.GeneralResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.location.until.MD5Until.md5;

@RestController
public class LoginController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Map<String,Object> login(String username,
                                    String password,
                                    HttpSession session){

        Map<String,Object> result = new HashMap<>();
        List<User> userList = userService.getAllusers();
        for (User users:userList) {
            if (users.getUsername().equals(username) && users.getPassword().equals(md5(password))) {
                if(users.getLevel().equals("admin")){
                    result.put("success", true);
                    result.put("role","admin");
                    session.setAttribute("user", 1);
                    return result;
                }else {
                    result.put("success",true);
                    result.put("role","common");
                    session.setAttribute("user",2);
                    return result;
                }
            } else {
                result.put("success", false);
                result.put("message", "用户名或者密码错误！！！");
                session.setAttribute("user", null);
            }
        }
        return result;
    }
    @ResponseBody
    @PostMapping("/register")
    public GeneralResponse register(String username1, String password1, String password2){
        System.out.println(username1);
        User user = new User();
        GeneralResponse response =new GeneralResponse();
        List<User> userList1 = userService.getAllusers();
        for (User users1:userList1){
            if(users1.getUsername().equals(username1)){
                response.setSuccess(false);
                response.setMessage("用户名重复！！");
                return response;
            }else if (password1.equals(password2)){
                user.setUsername(username1);
                user.setPassword(md5(password1));
                user.setLevel("common");
                response.setSuccess(true);
                response.setData(userService.add(user));
                response.setMessage("注册成功！！");
            }else {
                response.setSuccess(false);
                response.setMessage("两次密码不一致！！");
                return response;
            }
        }
        return response;
    }
}
